﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Windows;
using System.Windows.Threading;
using LockCrypt.Properties;

namespace LockCrypt {
    /// <summary>
    /// Erases the clipboard after a predefined interval.
    /// </summary>
    public class SecureClipboard {
        private static readonly DispatcherTimer _timer = new DispatcherTimer(DispatcherPriority.ApplicationIdle, Application.Current.Dispatcher);
        private static SecureString _copiedData = new SecureString();

        static SecureClipboard() {
            _timer.Tick += new EventHandler(_timer_Tick);
            ConfigureTimer();
            Settings.Default.SettingChanging += (s, e) => ConfigureTimer();
            Settings.Default.SettingsLoaded += (s, e) => ConfigureTimer();
            Settings.Default.SettingsSaving += (s, e) => ConfigureTimer();
        }

        /// <summary>
        /// Clears the clipboard when the timer ticks.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        static void _timer_Tick(object sender, EventArgs e) {
            //todo: make more secure?
            if(LockCryptWPFBLL.SecureStringToString(_copiedData) == Clipboard.GetText()) {
                Clipboard.Clear();
                _copiedData.Clear();
            }
        }

        /// <summary>
        /// Enables or disables the timer and updates the interval.
        /// </summary>
        public static void ConfigureTimer() {
            _timer.Stop();
            _copiedData.Clear();
            _timer.Interval = TimeSpan.FromSeconds(Settings.Default.SecureClipDelay);
            if(Settings.Default.SecureClip) {
                _timer.Start();
            }
        }

        /// <summary>
        /// Copies text to the clipboard.
        /// </summary>
        /// <param name="textToCopy">The text to copy.</param>
        public static void CopyToClipboard(string textToCopy) {
            if(!string.IsNullOrEmpty(textToCopy)) {
                Clipboard.SetText(textToCopy);
            }
            if(_timer.IsEnabled) {
                _copiedData = LockCryptWPFBLL.StringToSecureString(textToCopy);
            }
        }
    }
}
